using System;
using System.Collections.Generic;
using System.Text;

namespace SmartContentDB
{
    class SmartContentMySql : SmartContentDB
    {
        #region Variables
        private MySql.Data.MySqlClient.MySqlConnection connection;
        private MySql.Data.MySqlClient.MySqlCommand command;
        private MySql.Data.MySqlClient.MySqlTransaction trans;
        #endregion

        #region Constructor
        public SmartContentMySql()
        {
            connection = new MySql.Data.MySqlClient.MySqlConnection();
        }
        #endregion

        #region Override
        public override bool isConnected()
        {
            if (this.connection != null)
                return (this.connection.State == System.Data.ConnectionState.Open);
            return false;
        }

        public override void connect(string server, string port, string scheme, string user, string password)
        {
            connection.ConnectionString = "user id=" + user + "; " +
                "password=" + password + "; " +
                "database=" + scheme + "; " +
                "server=" + server + "; " +
                "port=" + port + "; " +
                "allow zero datetime=yes;";
            connection.Open();
            command = connection.CreateCommand();
            command.CommandText = "SET character_set_results=latin1";
            command.ExecuteNonQuery();

        }

        public override void disconnect()
        {
            connection.Close();
        }

        public override void writer(string sql, bool trans)
        {
            if (trans)
            {
                command.CommandText = sql;  
                command.ExecuteNonQuery();
            }
            else
            {
                command = connection.CreateCommand();
                command.CommandText = sql;
                command.ExecuteNonQuery();
            }
        }

        public override object reader(string sql)
        {
            command = connection.CreateCommand();
            command.CommandText = sql;
            return command.ExecuteReader();
        }

        public override void beginTrans()
        {
            trans = connection.BeginTransaction();
            command = connection.CreateCommand();
            command.Connection = this.connection;
            command.Transaction = this.trans;
        }

        public override void commitTrans()
        {
            if (trans == null)
                throw new Exception("Transaccion nula");
            trans.Commit();
        }

        public override void rollbackTrans()
        {
            trans.Rollback();
        }
        /*public override object getConnection()
        {
            return this.connection;
        }*/
        #endregion
    }
}
